package com.znow.admin.exception;

import com.znow.admin.system.security.enums.SysUserErrorEnums;
import com.znow.base.exception.GlobalDefaultExceptionHandler;
import com.znow.common.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常管理器
 *
 * @author Nemo
 * @date 2022/10/24
 */
@Slf4j
@RestControllerAdvice
public class AdminExceptionAdvice extends GlobalDefaultExceptionHandler {

    /**
     * 密码错误提示
     *
     * @param ex 异常
     * @return {@link CommonResult}<{@link ?}>
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    public CommonResult<?> badCredentialsException(BadCredentialsException ex) {
        return CommonResult.failed(SysUserErrorEnums.PASSWORD_ERROR);
    }

    /**
     * 密码错误提示
     *
     * @param ex 异常
     * @return {@link CommonResult}<{@link ?}>
     */
    @ExceptionHandler(value = UsernameNotFoundException.class)
    public CommonResult<?> usernameNotFoundException(UsernameNotFoundException ex) {
        return CommonResult.failed(SysUserErrorEnums.USERNAME_NOT_EXIST_ERROR);
    }

    /**
     * 密码错误提示
     *
     * @param ex 异常
     * @return {@link CommonResult}<{@link ?}>
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public CommonResult<?> accessDeniedException(AccessDeniedException ex) {
        return CommonResult.failed(SysUserErrorEnums.PERMISSION_DENIED);
    }
}
